<template>
	<div class="zh-examinationPaper-type">
		<nav-header>
			<!-- <div class="zh-h5-nav">
				<div 
					:class="activePanel === 'examinationPaper-type' ? 'active' : ''"
					@click="changePanel('examinationPaper-type')">题型管理</div>
				<div 
					:class="activePanel === 'relevance' ? 'active' : ''" 
					@click="changePanel('relevance')">题型关联</div>
			</div> -->
		</nav-header>

		<transition name="fade" mode="out-in" v-if="activePanel === 'examinationPaper-type'" >
			<div class="zh-table">
				<div class="zh-table-open clear">
                    <div class="zh-open-left fl">
                        <div class="open-width" style="width: 140px">
                            <el-select v-model="typeId" filterable placeholder="请选择题型模板">
                                <el-option
                                    v-for="item in typeBaseList"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id">
                                </el-option>
                            </el-select>
                        </div>
                        <el-button type="primary" @click="getList">搜索</el-button>
                        <el-button type="primary" @click="reset">重置</el-button>
                    </div>
					<div class="zh-open-right fr">
						<el-button type="primary" @click="saveBox()">新增</el-button>
						<el-button type="danger" @click="deleteMuilt_confirm">批量删除</el-button>
					</div>
				</div>
				<div class="zh-table-contents"
					v-loading="loading.status"
					:element-loading-text="loading.txt">
					<el-table
					    :data="listData"
					     @selection-change="tableSelectionChange"
					    border
					    max-height="600"
					    style="width: 100%">
					    <el-table-column
					      type="selection"
					      width="50"
					      align="center"
					      fixed>
					    </el-table-column>
					    <el-table-column
					      prop="name"
					      label="名称"
					      align="center"
					      show-overflow-tooltip>
					    </el-table-column>
                        <el-table-column
					      prop="base_name"
					      label="题型模板"
					      align="center"
					      show-overflow-tooltip>
					    </el-table-column>
                        <el-table-column
					      prop="common"
					      label="题型描述"
					      align="center"
					      show-overflow-tooltip>
					    </el-table-column>
					    <el-table-column
					      prop=""
					      label="状态"
					      align="center"
					      width="200"
					      show-overflow-tooltip
					      >
						     <template slot-scope="scope">
					      	  <div v-html="getStatus(scope.row.status)"></div>
					      	</template>
					    </el-table-column>
					    <el-table-column
					      prop="3"
					      label="操作"
					      align="center"
					      width="140"
					      show-overflow-tooltip
					      >
		      		      	<template slot-scope="scope">
		      		      		<template v-if="parseInt(scope.row.status) === 2 ">
		      		      			<el-button @click="change_confirm(scope.row,1)" type="text">启用</el-button>
		      		      		</template>
		      		      		<template v-if="parseInt(scope.row.status) === 1 ">
		      		      			<el-button @click="change_confirm(scope.row,2)" type="text">禁用</el-button>
		      		      		</template>
		      	      	        <el-button @click="saveBox(scope.row)" type="text">编辑</el-button>
		      	      	        <el-button @click="delete_confirm(scope.row)" type="text" class="delete-button">删除</el-button>
		      	      	    </template>
					    </el-table-column>
					</el-table>
				</div>
			</div>
		</transition>
		<transition name="fade" mode="out-in" v-if="activePanel === 'relevance'" >
			<zh-examination-paper-relevance />
		</transition>

		<!-- 添加/编辑题型 -->
		<el-dialog 
            :close-on-click-modal="false" 
            :close-on-press-escape="false" 
            :visible.sync="AddType" 
            :title="boxTitle" 
            class="addType" 
            width="550px">
			<el-form :model="addForm" :rules="rules" ref="addForm" status-icon label-position="left" label-width="100px">
			    <el-form-item label="题型名称：" prop="name">
			      	<el-input 
			      		v-model="addForm.name" 
			      		placeholder="请输入10个字以内" 
			      		autocomplete="off"
			      		:maxlength="parseInt(10)"
			      		clearable>
                    </el-input>
			    </el-form-item>
                <el-form-item label="题型模板：" prop="base_id">
                    <el-select v-model="addForm.base_id" placeholder="请选择题型模板" :disabled="addForm.status == 2">
                        <el-option v-for="(item, inx) in typeBase" :key="inx" :label="item.name" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="题型描述：" prop="base_common">
                    <el-input type="textarea" v-model="addForm.base_common" :rows="3"></el-input>
                </el-form-item>
			</el-form>

			<div slot="footer" class="dialog-footer">
			    <el-button @click="AddType = false">取消</el-button>
			    <el-button type="primary" @click="saveType">保存</el-button>			    
			</div>
		</el-dialog>

        <el-dialog 
            :close-on-click-modal="false" 
            :close-on-press-escape="false" 
            :visible.sync="showPassword" 
            title="管理员确认" 
            class="addType" 
            width="400px">
			<!-- <el-form :model="passForm" :rules="rules" ref="passForm" status-icon label-position="left" label-width="120px">
			    <el-form-item label="管理员密码：" prop="pass">
			      	<el-input 
                        type="password"
			      		v-model="passForm.pass" 
			      		autocomplete="off"
			      		clearable>
                    </el-input>
			    </el-form-item>
			</el-form> -->
				<!-- <span style="display: block;margin-bottom:22px">请输入超级管理员密码，并确认本次操作。</span> -->
				<el-input 
					placeholder="请输入超级管理员密码，并确认本次操作。"
					type="password"
					v-model="passForm.pass" 
					@keyup.enter.native="deleteType"
					autocomplete="off"
					clearable>
				</el-input>
			<div slot="footer" class="dialog-footer">
			    <el-button @click="showPassword = false">取消</el-button>
			    <el-button type="primary" @click="deleteType">保存</el-button>			    
			</div>
		</el-dialog>
	</div>
</template>
<script>
  	export default {
	    data() {
		    return {
                passForm: {
                    id: undefined,
                    pass: undefined
                },
                showPassword: false,
		    	loading:{
					status:false,
					txt:'获取数据...',
				},
		    	activePanel: 'examinationPaper-type',
		    	listData:[],
                selected:[],
                typeBase: [],
                typeBaseList: [],
                AddType: false,
	      		addForm: {
	      			id:0,
                    name: '',
                    base_common: '',
                    status: 1,
                    base_id: undefined
		        },
		        rules: {
		            name: [
									{ required: true, validator: this.validateName, trigger: 'blur' },
									{ pattern: this.rules.spaceKey.reg, message: this.rules.spaceKey.msg, trigger: ['blur', 'change']}
								],
								base_common: [
										{ required: true, message: '请输入题型描述', trigger: 'blur' },
										{ pattern: this.rules.spaceKey.reg, message: this.rules.spaceKey.msg, trigger: ['blur', 'change']}
								],
								base_id: [
										{ required: true, message: '请选择题型模板', trigger: 'change' }
								],
								pass: [
										{ required: true, message: '请输入管理员密码', trigger: 'blur' }
								]
		        },
		        statusArr:{
					1:'启用',
					2:'禁用',
				},
                boxTitle:'',
                typeId: 0, // 题型模板
		    }
		},
		created(){
			this.toggleView();
            this.getList();
            this.getTypeBase();
	    },
	    watch:{
	    	$route(){
	    		this.toggleView()
	    	},
	    	AddType(){
	    		if(this.AddType === false)
	    			this.$refs.addForm.resetFields()
	    	}
	    },
		methods: {
            /**
             * 获取全部题型模板
             */
            getTypeBase() {
            	let success = (res => {
                    this.typeBase = res.data;
                    this.typeBaseList = deep_clone(res.data);
                    this.typeBaseList.unshift({id: 0, name: '全部'})
                })
                
            	this.$ajax.get('api/newtest/get_question_type_base', {func: {success: success}});
            },
			changePanel(panel){
				this.activePanel = panel;
			},
			saveBox( obj = null ){
				this.AddType = true;
				if(is_empty(obj)){
					this.boxTitle = '添加题型';
					this.addForm.id = 0;
					this.addForm.name = '';
                    this.addForm.base_common = '';
                    this.addForm.status = 1;
                    this.addForm.base_id = undefined;
				}else{
					this.boxTitle = '编辑题型';
					this.addForm.id = obj.id;
					this.addForm.name = obj.name;
					this.addForm.status = obj.status;
                    this.addForm.base_common = obj.common;
                    this.addForm.base_id = obj.base_id;
				}
			},
			saveType(){
				this.$refs.addForm.validate((valid) => {
			        if (valid) {
	            		let success = ( data => {
	            			this.AddType = false;
	                		this.$message.success(data.msg)
	            			this.getList();
	            		});
	            		if( parseInt(this.addForm.id) > 0 ){
                            const params = {
                                id: this.addForm.id,
                                name: this.addForm.name,
                                base_id: this.addForm.base_id,
                                common: this.addForm.base_common
                            }

	            			this.$ajax.put('api/newtest/update_question_type', params, {func:{success:success}})
	            		}else{
                            const params = {
                                name: this.addForm.name,
                                base_id: this.addForm.base_id,
                                common: this.addForm.base_common
                            }

	            			this.$ajax.post('api/newtest/add_question_type', params, {func:{success:success}})
	            		}
			        } else {
			            return false;
			        }
			    });
			},
			change_confirm( obj, status ){
				let yes = ( data => {
					this.change(obj.id,status);
				})
				let cancel = ( data => {})
				this.e_confirm({yes:yes,cancel:cancel,txt:'确定将 '+obj.name+' 设置为 '+this.statusArr[parseInt(status)]+' 吗？'});
			},	
			change( id,status ){
		    	let success = ( data => {
		    		this.$message.success(data.msg)
					this.getList();
				});
		    	this.$ajax.post('api/test/change_type_status',{id:id,status:status},{func:{success:success}})
            },
            /**
             * 删除已创建题目的题型
             */
            deleteType() {
				if(this.passForm.pass == '') {
					this.$message.warning('请输入超级管理员密码')
                    return
				}
				const checkSuccess = (res => {
					let success = ( data => {
						this.showPassword = false;
						this.$message.success(data.msg);
						this.getList();
					});
					let params = {
						id: this.passForm.id,
						password: this.passForm.pass
					}

					this.$ajax.delete('api/newtest/del_question_type', {params, func: {success: success}})
				})

				const checkParams = {
					id: this.$g.user_id,
					password: this.passForm.pass
				}

				this.$ajax.get("api/user/check_user_by_id", {params: checkParams, func: {success: checkSuccess}});
            },
			delete(id){
                let self = this;

                setTimeout(() => {
                    self.$confirm('删除题型将同时删除该题型的所有题目，是否继续？', '声明', {
                        confirmButtonText: '继续',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        self.passForm.id = id;
                        
                        setTimeout(() => {
                            self.showPassword = true; 
                        	this.passForm.pass = '';
                        }, 300);
                    }).catch(() => {});
                }, 300);
		    },
		    delete_confirm(obj){
				let yes = ( data => {
					this.delete(obj.id);
				})
				let cancel = ( data => {})
				this.e_confirm({yes:yes,cancel:cancel,txt:'确定将 '+obj.name+' 删除吗？'});

			},
			deleteMuilt_confirm(){
				if( this.selected.length === 0 ) {
					this.$message.warning("请选择要删除的项");
					return false;
				}
				let yes = ( data => {
					this.muilDelete();
				})
				let cancel = ( data => {})
				this.e_confirm({yes:yes,cancel:cancel,txt:'确定要删除选中的项吗？'});

			},
			muilDelete(){
				let ids = '';

                this.selected.forEach((item, inx) => {
                    ids += (inx == 0 ? '' : ',') + item.id;
                })
                
				this.delete(ids);
			},
			 //选中
		    tableSelectionChange(val) {
                this.selected = val;
            },
			getStatus(val){
				return this.statusArr[parseInt(val)]
			},
			//获取数据
			getList(){
				this.loading.status = true;
            	let success = (data=>{
            		this.loading.status = false;
            		this.listData = data.data;
            	})
            	let fail = ( data => {
            		this.loading.status = false;
            		this.$message.error(data.msg)
                })
                let params = {
                    status: '1, 2',
                    type_id: this.typeId,
                }

            	this.$ajax.get('api/newtest/get_question_type',{params, func:{success:success,fail:fail}})
            },
			/**
             * 重置数据
             */
            reset() {
                this.typeId = 0;
                this.getList();
            },
			//验证
			validateName(rule, value, callback){
				console.log(value)
				if (value === '') {
					return callback(new Error('请输入内容'))
				} else if ( !validateName(value)) {
					return callback(new Error('请不要输入空格字符'))
				} else {
					callback()
				}
			},
			//记录导航状态
		    toggleView(){
		   		this.view = this.$route.name
		    },
		    handleSizeChange(val) {
		        console.log(`每页 ${val} 条`);
		    },
		    handleCurrentChange(val) {
		        console.log(`当前页: ${val}`);
		    }
		},
  	}
</script>
<style lang="scss">
	.zh-examinationPaper-type {
		.el-table__body-wrapper table tbody {
			td:nth-child(4) {
				padding: 0;
			}
		}
	}
</style>